<?php
$url="localhost:3306";
$user="root";
$password="";
$database="php";

$conn=mysqli_connect($url,$user,$password,$database);

if(!$conn){
    echo "error-msg:" . mysqli_connect_error();
    echo "<br>";
    echo "error-code:" . mysqli_connect_errno();
    echo "<br>";
    return;
}
echo "链接成功";
echo "<br>";
mysqli_query($conn,"set names utf8");


$name = "测试";
$price = 29.9;
$unit = "束";
$imageUrl = "/day03/images/Tulips.jpg";
// 2.执行sql语句(增删改)
// $sql = "insert into product " 
//         ." (p_name,p_price,p_unit,p_image_url) "
//         ." values " 
//         ." ('{$name}', {$price}, '{$unit}', '{$imageUrl}')";
// echo "<div>{$sql}</div>";

// // 执行增删改, 成功返回true, 失败返回false。
// $result = mysqli_query($conn, $sql);

//增加
function insert($name,$price,$unit,$imageUrl){
    $sql = "insert into product " 
    ." (p_name,p_price,p_unit,p_image_url) "
    ." values " 
    ." ('{$name}', {$price}, '{$unit}', '{$imageUrl}')";
    echo "<div>{$sql}</div>";
    return $sql;
}

$sql1=insert($name,$price,$unit,$imageUrl);
$result = mysqli_query($conn, $sql1);


//修改
function updateById($id,$name,$price,$unit,$imageUrl){
    $sql="update product"
        ." set "
        ." p_name='{$name}',p_price={$price},p_unit='{$unit}',p_image_url='{$imageUrl}'"
        ." where p_id={$id}";
    echo "<div>{$sql}</div>";
    return $sql;
}

// $sql2= updateById(5,$name,$price,$unit,$imageUrl);
// $result = mysqli_query($conn, $sql2);

//删除
function deleteById($id){
    $sql="delete from product"
        ." where p_id='{$id}'";
    echo "<div>{$sql}</div>";
    return $sql;
}
// $sql=deleteById(5);
// $result=mysqli_query($conn,$sql);





if($result){
    // 添加成功
    echo "<div>success</div>";

    // 再添加成功之后, 通过函数获取当前添加的数据的主键值
    $id = mysqli_insert_id($conn);
    echo "<div>id={$id}</div>";
} else {
    // 添加失败, 获取错误信息和错误码
    echo "error-msg:" . mysqli_error($conn);
    echo "<br>";
    echo "error-code:" . mysqli_errno($conn);
    echo "<br>";
}

mysqli_close($conn);

?>